package procilege.impl.expand;

import procilege.compute.ExprExpandTraveller;
import procilege.compute.PlaceTypeMetadata;
import procilege.compute.PlaceType;
import procilege.lang.BoolExprAnd;
import procilege.lang.BoolExprElement;
import procilege.lang.BoolExprOr;
import procilege.lang.ExprElement;

@PlaceTypeMetadata(type = BoolExprAnd.class)
public class BoolExprAndExpandPlace implements PlaceType<ExprExpandTraveller> {

	public void visit(ExprExpandTraveller tr, Object place) {

		BoolExprOr plus = new BoolExprOr();
		plus.add(new BoolExprAnd()); // the identity element.

		for (ExprElement t : ((BoolExprAnd) place).getTerms()) {

			tr.setout(t);
			Object r = tr.getPreviousVisitResult();
			if (r == null)
				continue;

			BoolExprOr terms = plus;
			plus = new BoolExprOr();
			if (r instanceof BoolExprOr) {

				for (BoolExprElement rt : (BoolExprOr) r) {
					for (BoolExprElement lt : terms) {

						plus.add(new BoolExprAnd(lt, rt));
					}
				}
			} else {

				for (BoolExprElement lt : terms) {

					plus.add(new BoolExprAnd(lt, (BoolExprElement) r));
				}
			}
		}

		tr.result(plus);
	}
}